package club.janna.rpcdemo.disruptor;

import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;

@Slf4j
public class DisruptorDemo {

    static class EventObject {

        public EventObject() {
            System.out.println("event 被创建");
        }

        int value;

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        ThreadFactory factory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                System.out.println("创建一个线程");
                return new Thread(r);
            }
        };
        Disruptor<EventObject> disruptor = new Disruptor<>(EventObject::new, 8, (ThreadFactory) Thread::new);
        disruptor.handleEventsWith(((event, sequence, endOfBatch) -> {
            log.info("{} - {}", event, event.getValue());
        }));

        disruptor.start();

        for (int i = 0; i < 10; i++) {
            final int ii = i;
            disruptor.publishEvent(((event, sequence) -> {
                event.setValue(ii);
            }));
        }
    }
}
